package zd.cornermemory.ui;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.RadioGroup;
import android.widget.TextView;

import zd.cornermemory.R;
import zd.cornermemory.fragment.graph.GraphFragment;
import zd.cornermemory.fragment.graph.HistFragment;

public class GraphicActivity extends BaseActivity {

    private HistFragment  mFrag1;
    private GraphFragment mFrag2;

    private TextView     cj_group;
    private RadioGroup   radio_group;
    private int          currentPos;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_graphic);
        currentPos = getIntent().getExtras().getInt("currentPos");
        String title  = getIntent().getExtras().getString("title");
        cj_group = findViewById(R.id.cj_group);
        cj_group.setText(title);
        radio_group = findViewById(R.id.radio_group);
        selectTab(0);
        radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.radio_0:
                        selectTab(0);
                        break;
                    case R.id.radio_1:
                        selectTab(1);
                        break;
                }
            }
        });
        setBackImage();
    }

    //进行选中Tab的处理
    private void selectTab(int i) {
        //获取FragmentManager对象
        FragmentManager manager = getSupportFragmentManager();
        //获取FragmentTransaction对象
        FragmentTransaction transaction = manager.beginTransaction();
        //先隐藏所有的Fragment
        hideFragments(transaction);
        switch (i) {
            //当选中点击Tab时
            case 0:
                //设置ImageButton为选中
                //如果对应的Fragment没有实例化，则进行实例化，并显示出来
                if (mFrag1 == null) {
                    mFrag1 = new HistFragment();
                    transaction.add(R.id.id_content, mFrag1);
                } else {
                    //如果对应的Fragment已经实例化，则直接显示出来
                    transaction.show(mFrag1);
                }
                break;
            case 1:
                if (mFrag2 == null) {
                    mFrag2 = new GraphFragment();
                    transaction.add(R.id.id_content, mFrag2);
                } else {
                    transaction.show(mFrag2);
                }
                break;

        }
        //提交事务
        transaction.commit();
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (mFrag1 != null) {
            transaction.hide(mFrag1);
        }
        if (mFrag2 != null) {
            transaction.hide(mFrag2);
        }
    }

    public int getCurrentPos() {
        return currentPos;
    }
}
